package com.xz.util;

import com.xz.util.api.vo.Result;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.UUID;

/**
 * 对上传的图片进行操作
 *
 * @author zagwk
 * @version 1.0
 * @date 2020/7/4 13:44
 */
public class PhotoUtil {

    public static String memoryPhoto(MultipartFile imgFile) throws IOException {
        String originalFilename = imgFile.getOriginalFilename();//获取原始文件名
        if (originalFilename != null && !originalFilename.equals("")) {
            int index = originalFilename.lastIndexOf(".");//找到 . 的位置
            String suffix = originalFilename.substring(index);//根据 . 的位置进行分割，拿到文件后缀名
            String fileName = UUID.randomUUID().toString() + suffix;//uuid生成新的文件名

            //将图片保存到本地/usr/etc/images/Folder
            File file = new File("/usr/local/etc/images");
            if (!file.exists()) {
                file.mkdirs();
            }
            String path = "/usr/local/etc/images/" + fileName;
            //实现上传
            imgFile.transferTo(new File(path));

            return "images/"+fileName;
        }
        return null;
    }

    /**
     * 上传文件形式，返回路径
     * @param imgFile
     * @return
     * @throws IOException
     */
    /*public static String uploadPhone(MultipartFile imgFile) throws IOException{
        String originalFilename = imgFile.getOriginalFilename();//获取原始文件名
        if (originalFilename != null && !originalFilename.equals("")) {
            int index = originalFilename.lastIndexOf(".");//找到 . 的位置
            String suffix = originalFilename.substring(index);//根据 . 的位置进行分割，拿到文件后缀名
            String fileName = UUID.randomUUID().toString() + suffix;//uuid生成新的文件名

            //将图片保存到本地/usr/etc/images/Folder
            File file = new File("F:\\img");
            if (!file.exists()) {
                file.mkdirs();
            }
            String path = "F:\\img/" + fileName;
            //实现上传
            imgFile.transferTo(new File(path));

            return path;
        }
        return null;
    }*/

    /**
     * @return
     * @throws IOException
     */
    public Result GenerateImage(String base64Data) throws IOException {
        String dataPrix = ""; //base64格式前头
        String data = "";//实体部分数据
        if (base64Data == null || "".equals(base64Data)) {
            return Result.error("上传失败，上传图片数据为空");
        } else {
            String[] d = base64Data.split("base64,");//将字符串分成数组
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                return Result.error("上传失败，数据不合法");
            }
        }
        String suffix = "";//图片后缀，用以识别哪种格式数据
        //编码的jpeg图片数据
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
            //编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
            //编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".png";
        } else {
            return Result.error("上传图片格式不合法");
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String tempFileName = uuid + suffix;
        String imgFilePath = "/usr/local/etc/images/" + tempFileName;//新生成的图片
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    //调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return Result.ok("/usr/local/etc/images/"+tempFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传图片失败");
        }

    }

    /**
     * 删除本地或服务器储存的图片
     * @param path
     * @return
     */
    public static String delFile(String path){
        String resultInfo = null;
        int lastIndexOf = path.lastIndexOf("/");
        String img_path = path.substring(lastIndexOf + 1,path.length());
        System.out.println(img_path);
        img_path = "/usr/local/etc/images/" + img_path;
//        img_path = "/usr/etc/images/Folder/" + img_path;
        File file = new File(img_path);
        if(file.exists()){
            if(file.delete()){
                resultInfo = "删除成功！";
            }else {
                resultInfo = "删除失败！";
            }
        }else {
            resultInfo = "文件不存在";
        }
        return resultInfo;
    }
    public static void main(String[] args) throws ParseException {
     String ss =   delFile("https://www.xzrenli.cn/images/Folder/123456.jpg");
        System.out.println(ss);
    }



}